# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,subprocess,threading,time
from piHAcore.servers import (INPUTq)

logger = logging.getLogger()



def delay(data):
    if isinstance(data,list):
        item = data
    else:
        item = data.split()
    t = int(item[0])
    if t > 360: t = 360
    if t < 1: t = 1
    return delayinput(t,' '.join(item[1:]),INPUTq)


def delayinput(mn,data,inputq):
    logger.debug("Delay execution of %s for %s mins",repr(data),repr(mn))
    d = threading.Timer(int(mn)*60,delayexe,[data,inputq,])
    d.name = 'TimerDelayExe_' + data.replace(' ','_')
    d.daemon = True
    d.start()
    return


def delayexe(data,inputq):
    try:
        inputq.put_nowait(data)
    except:
        pass
    return


def pollpopen(popid):
    if popid:
        retcode = popid.poll()
        if retcode == 0:
            return True
    return False


def shellexe(data):
    logger.debug("Execution SHELL of %s",repr(data))
    args = data.split()
    popid = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    p = threading.Timer(5, pollpopen, [popid,])
    p.__name__ = 'TimerSHELLScript_' + data.replace(' ','_')
    p.daemon = True
    p.start()
    return True


def tempo(data):
    if isinstance(data,list):
        ts = data[0]
    else:
        ts = data
    t = int(ts)
    if t > 120: t = 120
    if t < 1: t = 5
    logger.debug("Script execution PAUSE for %s seconds",repr(t))
    time.sleep(t)
